<template>
    <el-dialog :width="dialog.width || '40%'"
               :visible="dialog.visible"
               :modal-append-to-body="false"
               :close-on-click-modal="false"
               @close="close">
        <div slot="title" class="text-center">
            <span class="font-s20">
                <icon name="create"></icon>
                创建管理员
            </span>
        </div>
        <el-form ref="modelForm"
                 size="medium"
                 label-position="top"
                 :model="model"
                 :rules="rules"
                 :inline-message="true"
                 :status-icon="true"
                 @submit.native.prevent>
            <el-scrollbar class="r-custom-scrollbar custom-scroll-height">
                <div class="pl-20 pr-20">
                    <!-- 表单 -->
                    <el-form-item label="超级管理员" prop="is_super">
                        <el-switch v-model="model.is_super"
                                   :width="35"
                                   active-color="#28a745"
                                   :active-value="1"
                                   :inactive-value="0">
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="用户名" prop="username">
                        <el-input placeholder="用户名"
                                  maxlength="16"
                                  v-model="model.username"></el-input>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input type="text"
                                  placeholder="密码"
                                  maxlength="16"
                                  show-password
                                  v-model="model.password"></el-input>
                    </el-form-item>

                    <el-form-item label="手机号码" prop="mobile">
                        <el-input placeholder="手机号码"
                                  maxlength="11"
                                  v-model="model.mobile"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input type="email"
                                  placeholder="邮箱"
                                  maxlength="50"
                                  v-model="model.email"></el-input>
                    </el-form-item>

                    <el-form-item label="锁定" prop="is_lock">
                        <el-switch v-model="model.is_lock"
                                   :width="35"
                                   active-color="#28a745"
                                   :active-value="1"
                                   :inactive-value="0">
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="所属角色" prop="roles">
                        <div class="el-row--flex">
                            <el-select v-model="model.roles"
                                       multiple
                                       placeholder="请选择"
                                       style="width: 100%;">
                                <el-option v-for="(item, index) in options"
                                           :key="index"
                                           :label="item.name"
                                           :value="item.id">
                                    <icon :name="item.icon"></icon> {{ item.name }}
                                </el-option>
                            </el-select>
                            <div class="pl-10">
                                <el-button type="info"
                                           icon="el-icon-refresh"
                                           :loading="optionLoading"
                                           @click="loadOptions()">加载</el-button>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="描述" prop="description">
                        <el-input type="textarea"
                                  rows="2"
                                  v-model="model.description"
                                  :maxlength="50"
                                  show-word-limit></el-input>
                    </el-form-item>
                </div>
            </el-scrollbar>
        </el-form>
        <div class="mt-20 text-right">
            <el-button type="text" size="medium" @click="close">取消</el-button>
            <el-button type="primary"
                       size="medium"
                       icon="moe-icon moe-icon-save"
                       :loading="saveLoading"
                       native-type="submit"
                       @click="submitForm('modelForm')">确定
            </el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Prop, Emit, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'

import { errorMessage, successMessage, toJson } from '@/utils'
import { validateMobile, validateChineseUsername } from '@/utils/rules'

const roleModule = namespace('cms/role')
const adminUserModule = namespace('cms/adminUser')

@Component
export default class Create extends Vue {
  @Prop({type: Object, default: {}}) dialog!: any

  // Vuex
  @roleModule.State options!: Array<any>
  @roleModule.Action getOptions!: (payload: any) => Promise<any>
  @adminUserModule.Action store!: (payload: any) => Promise<any>

  // form模型
  private model: any = {
    is_super: 0,
    username: '',
    password: '',
    mobile: '',
    email: '',
    is_lock: 0,
    roles: [],
    description: ''
  }

  // 验证规则
  private rules: any = {
    username: [
      {required: true, message: '请填写用户名', trigger: 'blur'},
      {validator: validateChineseUsername, trigger: 'blur'}
    ],
    password: [
      {required: true, message: '请填写密码', trigger: 'blur'},
      {min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur'}
    ],
    mobile: [
      {required: true, message: '请填写手机号码', trigger: 'blur'},
      {validator: validateMobile, trigger: 'blur'}
    ]
  }

  private optionLoading: boolean = false // 选项加载状态
  private saveLoading: boolean = false // 保存加载状态

  // 钩子
  created() {
    this.options.length <= 0 && this.loadOptions()
  }

  /**
   * 载入选项
   */
  private loadOptions(): void {
    this.optionLoading = true
    this.getOptions({}).then((res: any) => {
      this.optionLoading = false
    }).catch((err: any) => {
      this.optionLoading = false
    })
  }

  /**
   * 提交表单
   *
   * @param name
   */
  private submitForm(name: string): void | boolean {
    (this.$refs[name] as any).validate((valid: boolean) => {
      if (valid) {
        this.saveLoading = true
        this.store({param: this.model}).then((res: any) => {
          this.saveLoading = false
          if (res.status !== 200) {
            errorMessage(res.message)
            return false
          }

          successMessage(res.message)
          this.close()
        }).catch((err: any) => {
          this.saveLoading = false
        })
      }
    })
  }

  /**
   * 重置表单
   *
   * @param name
   */
  private resetForm(name: string): void {
    (this.$refs[name] as any).resetFields()
  }

  @Emit()
  close(): void {
    this.resetForm('modelForm')
    this.saveLoading = false
  }
}
</script>

<style lang="scss" scoped>
.custom-scroll-height {
    height: 400px;
}
</style>
